const Controller = require('egg').Controller;

class ApplesController extends Controller{
  async index(){  //get：获取所有数据
    let data = await this.ctx.service.apples.getApples();
    this.ctx.body = {
      code:200,
      message:'success',
      data:data
    };
    this.ctx.status = 200;
  }
  async show(){ //get：根据id获取数据
    let { id } = this.ctx.params; //获取路由参数
    let { name } = this.ctx.query;//获取用户入参
    let data = await this.ctx.service.apples.getDetail(id);
    this.ctx.body = {
      code:200,
      message:'success',
      data:data,
      query:name,
      params:id
    };
    this.ctx.status = 200;
  }
  async create(){ //post：新增数据
    let data = this.ctx.request.body;  //请求体数据
    let res = await this.ctx.service.apples.addApple(data);
    this.ctx.body={
      code:200,
      data:{
        ...res,
        apples:{...data,id:res.insertId}
      }
    };
    this.status = 200;
  }
  async update(){ //put:修改数据
    let { id } = this.ctx.params; //获取路由参数
    let data = this.ctx.request.body;  //请求体数据
    data.id = id;
    let res = await this.ctx.service.apples.updateApple(data);
    this.ctx.body={
      code:200,
      data:res
    };
    this.status = 200;
  }
  async destroy(){ //delete:删除数据
    let { id } = this.ctx.params; //获取路由参数
    // let res = await this.ctx.service.apples.deleteApple(id);
    let res = await this.ctx.service.apples.updateApple({id:id,isEaten:true});
    this.ctx.body={
      code:200,
      data:res
    };
    this.status = 200;
  }
}
module.exports = ApplesController;
